<?php

class Pages_Model extends Model {

	function Pages_Model()
	{
		parent::Model();
	}
	
	//todo: optimize
	function set_page($page) {
		//validate
		if ($page['title'] == '' || $page['content'] == '') {
			return false;
		}
		//is this a new page?
		if ($page['new'] == "TRUE") {
			//create a blank entry in the pages table
			$this->new_page();
		}
		
		//we want page2 = page except without ['new']
		$page2['id'] 			= 	$page['id'];
		$page2['title'] 		= 	$page['title'];
		$page2['content'] 		= 	$page['content'];
		
		$this->db->where('id', $page2['id']);
		$this->db->update('pages', $page2);
		
		return true;
		
	}
	
	//todo: optimize
	function get_page($pageid) {
		
		$query = $this->db->query('SELECT * FROM pages WHERE id = ' . $pageid);
		$results = $query->result();
		
		return $results[0];
		
	}
	
	function get_page_from_slug($slug) {
		$this->db->where('slug', $slug);
		$query = $this->db->get('pages');
		$results = $query->result();
		return $results[0];
	}
	
	//todo: optimize
	function get_pages($offset = 0) {
		//get everything from the pages table
		$this->db->order_by("date", "desc");
		$query = $this->db->get('pages', 10, $offset);
		
		
		return $query->result();
		
	}
	
	function get_all_pages() {
		$query = $this->db->get('pages');
		return $query->result();
	}
	
	//todo: optimize
	function get_title($pageid) {
		$this->db->where('id', $pageid);
		$query = $this->db->get('pages');
		$results = $query->result();
		return $results[0]->title;
	}
	
	//todo: optimize
	function number_pages() {
		$query = $this->db->query('SELECT * FROM pages');
		$result = $query->result();
		
		return count($result);
	}
	
	//todo: optimize
	function new_page() {
		$blank['title'] = '';
		$blank['content'] = '';
		$blank['id'] = $this->number_pages() + 1;
		
		$this->db->insert('pages', $blank);
	}
	
	//todo: optimize
	function delete_page($pageid) {
		$this->db->delete('pages', array('id' => $pageid));
		return true;
	}
	
	//todo: optimize
	function get_oldest_year() {
		$query = $this->db->query('SELECT MIN(date) FROM pages');
		$results = $query->result();
		//get the year from it
		foreach ($results[0] as $r) {
			//that query make a weird unusable variable name in the object. this is a hack
			//to get at the date
			$oldestyear = substr($r,0,4);
			break;
		}
		return $oldestyear;
	}



	
}
?>